package com.estudy.contorller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.estudy.entity.Knowledge;
import com.estudy.entity.ResultVo;
import com.estudy.entity.User;
import com.estudy.service.FileService;
import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author: sun.hongliang
 * @create: 2019/09/04 10:53
 */
@Controller
@RequestMapping("/file")
public class FileController {
    private static final Logger logger = Logger.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    @RequestMapping("/uploadPage")
    public ModelAndView fileUpdoadPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("file/file-upload");
        return modelAndView;
    }

    @RequestMapping("/knowledgePage")
    public ModelAndView knowledgePage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("file/knowledge-page");
        return modelAndView;
    }

    @RequestMapping("/editPage")
    public String editPage(Map<String, Object> map, String fid) {
        Knowledge knowledge = fileService.queryFileById(fid);
        logger.info("konwledge:" + JSON.toJSONString(knowledge, SerializerFeature.WriteMapNullValue));
        map.put("konwledge", knowledge);
        return "file/knowledge-edit";
    }

    @RequestMapping("/dataList")
    @ResponseBody
    public String queryAllFiles() {
        try {
            Map<String, Object> map = Maps.newHashMap();
            List<Knowledge> knowledges = fileService.queryAllFiles();
            map.put("data", knowledges);
            map.put("recordsTotal", knowledges.size());
            map.put("recordsFiltered", knowledges.size());
            map.put("pageNum", 1);
            return JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
        } catch (Exception e) {
            logger.error("queryAllFiles error", e);
        }
        return "";
    }

    @RequestMapping("/edit")
    @ResponseBody
    public String fileEdit(@ModelAttribute Knowledge knowledge, String status) {
        ResultVo resultVo = new ResultVo();
        try {
            if ("ON".equalsIgnoreCase(status) || "通过".equals(status)) {
                knowledge.setApproval(1);
            } else {
                knowledge.setApproval(2);
            }
            fileService.updateKnowledge(knowledge);
            resultVo.setStatus(200);
            resultVo.setMessage("保存成功");
        } catch (Exception e) {
            logger.error("fileEdit error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("保存失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/del")
    @ResponseBody
    public String fileDel(String id) {
        ResultVo resultVo = new ResultVo();
        try {
            fileService.delFileInfo(id.trim());
            resultVo.setStatus(200);
            resultVo.setMessage("删除成功");
        } catch (Exception e) {
            logger.error("fileEdit error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("删除失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/save")
    @ResponseBody
    public String fileSave(@ModelAttribute Knowledge knowledge, HttpServletRequest request) {
        ResultVo resultVo = new ResultVo();
        try {
            User user = (User) request.getSession().getAttribute("u");
            if (user == null) {
                user = new User();
                user.setId("1");
            }
            knowledge.setUid(Integer.parseInt(user.getId()));
            logger.info("knowledge:" + JSON.toJSONString(knowledge));
            if (StringUtils.isEmpty(knowledge.getFid())) {
                knowledge.setFid(UUID.randomUUID().toString().replaceAll("-", ""));
            }
            fileService.saveKnowledge(knowledge);
            resultVo.setStatus(200);
            resultVo.setMessage("保存成功");
        } catch (Exception e) {
            logger.error("fileSave error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("保存失败");
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }

    @RequestMapping("/uploadFile")
    @ResponseBody
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file) {
        ResultVo resultVo = new ResultVo();
        URL resource = this.getClass().getResource("/");
        String path = resource.getPath() + "temp";
        System.out.println(path);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        OutputStream os = null;
        InputStream is = null;
        try {
            String revPath = path + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
            os = new FileOutputStream(revPath);
            is = file.getInputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = is.read(b)) != (-1)) {
                os.write(b, 0, length);
            }
            os.flush();
            resultVo.setStatus(200);
            resultVo.setMessage("上传文件成功");
            Map<String, Object> map = Maps.newHashMap();
            map.put("filename", file.getOriginalFilename());
            map.put("path", revPath);
            map.put("fid", UUID.randomUUID().toString().replaceAll("-", ""));
            resultVo.setData(map);
        } catch (Exception e) {
            logger.error("uploadfile error", e);
            resultVo.setStatus(500);
            resultVo.setMessage("上传失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    logger.error("os close error", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("is close error", e);
                }
            }
        }
        return JSON.toJSONString(resultVo, SerializerFeature.WriteMapNullValue);
    }
}
